package cn.wenhe9.yygh.filter;

import cn.wenhe9.yygh.common.exception.YyghException;
import cn.wenhe9.yygh.common.helper.JwtHelper;
import cn.wenhe9.yygh.common.result.ResultCodeEnum;
import cn.wenhe9.yygh.common.result.ResultResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author DuJinliang
 * 2022/4/5
 */
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Resource
    private ObjectMapper objectMapper;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (HttpMethod.OPTIONS.equals(request.getMethod())){
            return chain.filter(exchange);
        }

        String path = request.getURI().getPath();
        log.info("path={}", path);

        //内部服务接口，不允许外部访问
        if (antPathMatcher.match("/**/inner/*", path)){
            ServerHttpResponse response = exchange.getResponse();
            try {
                return out(response, ResultCodeEnum.PERMISSION);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                throw new YyghException(ResultCodeEnum.FAIL);
            }
        }

        //api接口，异步请求，检验用户必须登录
        if (antPathMatcher.match("/api/**/auth/*", path)){
            Long userId = this.getUserId(request);

            if (null == userId){
                ServerHttpResponse response = exchange.getResponse();
                try {
                    return out(response, ResultCodeEnum.LOGIN_AUTH);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                    throw new YyghException(ResultCodeEnum.FAIL);
                }
            }
        }
        return chain.filter(exchange);
    }

    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) throws JsonProcessingException {
        ResultResponse<Object> result = ResultResponse.build(null, resultCodeEnum);
        byte[] bytes = objectMapper.writeValueAsString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    private Long getUserId(ServerHttpRequest request){
        String token = "";

        HttpHeaders headers = request.getHeaders();
        List<String> tokenList = request.getHeaders().get("token");
        if (null != tokenList){
            token = tokenList.get(0);
        }
        if (!StringUtils.isEmpty(token)){
            return JwtHelper.getUserId(token);
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
